package com.citi.xylophone.phoneEmulator.view.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.citi.xylophone.phoneEmulator.audio.AudioManager;
import com.citi.xylophone.phoneEmulator.global.GlobalSwap;
import com.citi.xylophone.phoneEmulator.model.xml.ConfigSource;
import com.citi.xylophone.phoneEmulator.model.xml.ConfigTestSource;
import com.citi.xylophone.phoneEmulator.model.xml.Param;
import com.citi.xylophone.phoneEmulator.view.MainPanelview;

public class ButtonConectListener implements ActionListener {

	private MainPanelview mainPanelview;
	
	
	public ButtonConectListener(MainPanelview mainPanelview) {
		super();
		this.mainPanelview = mainPanelview;
	}



	public void actionPerformed(ActionEvent actionevent) {
	
		if (GlobalSwap.getConnect()){
			
			System.out.println("Disconect...");
			GlobalSwap.setConnect(false);
			mainPanelview.getButton11().setText("connect");
			mainPanelview.getComboBox1().setEnabled(true);
			mainPanelview.getComboBox2().setEnabled(false);
			mainPanelview.getComboBox3().setEnabled(false);
			mainPanelview.getButton16().setEnabled(false);
			
			mainPanelview.disableActions();
			mainPanelview.disableDial();
			try {
				AudioManager.stopAudio();
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			
			
	
			
			
		} else {
			
			System.out.println("Connect...");
			GlobalSwap.setConnect(true);
			
			mainPanelview.getComboBox1().setEnabled(false);
			mainPanelview.getComboBox2().setEnabled(true);
			mainPanelview.getComboBox3().setEnabled(true);
			mainPanelview.getButton16().setEnabled(true);
			mainPanelview.getButton11().setText("disconect");
			
			mainPanelview.getComboBox2().removeAllItems();
			mainPanelview.getComboBox3().removeAllItems();
			
			GlobalSwap.getConfig();
			
			for (ConfigSource configSource:GlobalSwap.getConfig().getDestinationList()){
				
				if (configSource.getName().equals(mainPanelview.getComboBox1().getSelectedItem())){
					
					GlobalSwap.setURL(configSource.getUrl());
					GlobalSwap.setAudioIP(configSource.getAudioIP());
					
					if (configSource.getTestSourceList()!=null){
						for (ConfigTestSource configTestSource : configSource.getTestSourceList()){
							mainPanelview.getComboBox2().addItem(configTestSource.getName());
						}
					}
					
					if (configSource.getParams()!=null){
						for (Param param : configSource.getParams()){
							mainPanelview.getComboBox3().addItem(param.getName());
						}
					}
				}
			}
			
			mainPanelview.disableActions();
			mainPanelview.disableDial();
			mainPanelview.getButton17().setEnabled(true);
			
			
		}
	}
}
